package cn.tedu.weibo2.controller;

import cn.tedu.weibo2.mapper.WeiboMapper;
import cn.tedu.weibo2.vo.User;
import cn.tedu.weibo2.vo.Weibo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@RestController
public class WeiboController {

    @Autowired
    WeiboMapper mapper;

    @RequestMapping("/send")
    public int send(Weibo weibo, MultipartFile picFile, HttpSession session) throws IOException {
        //获取用户ID判断是否登录
        User u = (User) session.getAttribute("u");
        if (u == null){
            return 2;
        }

        String fileName = picFile.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        fileName = UUID.randomUUID()+suffix;

        String dirPath = "D:/upload/";
        File dirFile = new File(dirPath);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }

        String filePath = dirPath+fileName;
        picFile.transferTo(new File(filePath));

        weibo.setAuthor(u.getNick());
        weibo.setUrl("/"+fileName);
        weibo.setUserId(u.getId());
        weibo.setCreated(new Date());
        mapper.insert(weibo);
        return 1;
    }


    @RequestMapping("/weibo/select/my")
    public List<Weibo> myWeibo(){
        return mapper.select();
    }

    @RequestMapping("/delete")
    public void delete(int id){
        String fileName = mapper.select(id);
        String dirName = "D:/upload"+fileName;
        File file = new File(dirName);
        File[] subs = file.listFiles();


        mapper.delete(id);
    }
}
